package com.wjk.kylin.modules.system.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjk.kylin.modules.system.user.entity.UserRole;
import com.wjk.kylin.modules.system.user.mapper.UserRoleMapper;
import com.wjk.kylin.modules.system.user.service.IUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 用户和角色关联表 服务实现类
 * </p>
 */
@Service
@Transactional(readOnly=true)
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Override
    @Transactional(readOnly=false)
    public void deleteByUserIds(List<String> userIds) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", userIds);
        super.remove(wrapper);
    }

    @Override
    @Transactional(readOnly=false)
    public void deleteByRoleIds(List<String> roleIds) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.in("role_id", roleIds);
        super.remove(wrapper);
    }

    @Override
    public List<String> findRoleListByUserId(String userId) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", userId);

        List<UserRole> list = super.list(wrapper);

        return list.stream().map(UserRole::getRoleId).distinct().collect(Collectors.toList());
    }

    @Override
    public void save(String userId, List<String> roleIds) {
        List<UserRole> userRoleList = new ArrayList<>();
        roleIds.forEach(roleId->{
            UserRole userRole = new UserRole();

            userRole.setRoleId(roleId);
            userRole.setUserId(userId);

            userRoleList.add(userRole);
        });

        super.saveBatch(userRoleList);
    }
}
